<template>
    <div class="main_box">
      <div class="add_wrap">
        <!-- <div class="left-content"> -->
            <div class="tit">
                <h2>医院信息</h2>
                <el-button
                    plain
                    size="small"
                    type="success"
                    icon="fa fa-mail-forward"
                    @click="returnList"
                >
                    返 回</el-button
                >
            </div>
        <el-form
          :model="reportForm"
          ref="reportForm"
          label-width="200px"
          :rules="roleRules"
        >
          <el-row>
            <el-form-item label="医院名称" prop="hospitalId">
              <el-select
                v-model="reportForm.hospitalId"
                filterable
                clearable
                reserve-keyword
                :loading="loadingIns"
                placeholder="请选择医院"
                @change="hospitalChange"
              >
                <el-option
                  v-for="item in pickHospitalList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
  
            <el-form-item label="科室名称" prop="officeId">
              <el-select
                v-model="reportForm.officeId"
                filterable
                clearable
                reserve-keyword
                :loading="loadingIns"
                placeholder="请选择科室"
                @change="officeChange"
              >
                <el-option
                  v-for="item in pickOfficeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <a
                href="javascript:void(0);"
                @click="addOffice"
                style="margin-left: 230px"
                >快速创建</a
              >
            </el-form-item>
  
            <el-form-item label="医生名称" prop="doctorId">
              <el-select
                v-model="reportForm.doctorId"
                filterable
                clearable
                reserve-keyword
                :loading="loadingIns"
                placeholder="请选择医生"
              >
                <el-option
                  v-for="item in pickDoctorList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <a
                href="javascript:void(0);"
                @click="addDoctor"
                style="margin-left: 230px"
                >快速创建</a
              >
            </el-form-item>
  
           
  
          </el-row>
  
          <div class="tit">
            <h2>项目信息</h2>
          </div>
          <el-row>
            <el-form-item label="医院项目" prop="hospitalItemIdList" v-show="itemDisabled">
              <el-select
                v-model="reportForm.hospitalItemIdList"
                filterable
                clearable
                multiple
                reserve-keyword
                :loading="loadingIns"
                placeholder="请选择医院项目"
                @change="hospitalItemChange"
              >
                <el-option
                  v-for="item in pickHospitalItemList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="医检项目" prop="itemNames" v-if="!itemDisabled">
              <el-select
                v-model="reportForm.insItemIdList"
                filterable
                multiple
                placeholder="请选择医检名称"
                @change="itemListChange"
              >
                <el-option
                  v-for="item in itemNameList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目名称" prop="itemName">
            <!-- :disabled="!itemDisabled" -->
              <el-input
                v-model.trim="reportForm.itemName"
                :disabled="isForbidItemName"
              ></el-input>
            </el-form-item>
            <el-form-item label="样本-1" prop="sampleTypeOne">
              <el-select
                v-model="sampleTypeData.sampleTypeOne"
                filterable
                clearable
                reserve-keyword
                placeholder="请选择项目样本"
              >
                <el-option
                  v-for="item in pickSampleTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button
                @click="addSubSampleType()"
                icon="el-icon-plus"
                plain
                round
                type="success"
                size="mini"
              ></el-button>
            </el-form-item>
            <el-form-item
              prop="sampleTypeList"
              v-for="(item, index) in sampleTypeData.sampleTypeList"
              :label="'样本-' + (index + 2)"
              :key="'sampleTypeList' + index"
            >
              <el-select
                v-model.lazy="item.id"
                filterable
                clearable
                reserve-keyword
                placeholder="请选择样本类型"
              >
                <el-option
                  v-for="item in pickSampleTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button
                @click="deleteSubSampleType(index)"
                icon="el-icon-close"
                plain
                round
                type="danger"
                size="mini"
              ></el-button>
            </el-form-item>
          </el-row>
  
          <div class="tit" v-if="userRole === 1">
            <h2>医检机构</h2>
          </div>
          <el-row v-if="userRole === 1">
            <el-form-item label="医检名称" prop="institutionId">
              <el-select
                v-model="reportForm.institutionId"
                filterable
                clearable
                reserve-keyword
                :loading="loadingIns"
                placeholder="请选择医检机构"
                @focus="listInstitution"
                @change="institutionChange"
              >
                <el-option
                  v-for="item in pickInstitutionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
  
            <el-form-item label="科室名称" prop="insOfficeId">
              <el-select
                v-model="reportForm.insOfficeId"
                filterable
                clearable
                reserve-keyword
                placeholder="请选择科室"
              >
                <el-option
                  v-for="item in pickInsOfficeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
  
          <div class="tit">
            <h2>基础信息</h2>
          </div>
          <el-row>
            <el-form-item v-if="false" label="查询号" prop="searchCode">
              <el-input v-model.trim="reportForm.searchCode"></el-input>
            </el-form-item>
            
            <el-form-item label="医检条码号" prop="insReportCode">
              <el-input
                v-model.trim="reportForm.insReportCode"
                @blur="checkInsCodeIsExist"
              >
              </el-input>
              <br /><span
                id="insCodeHides"
                :hidden="insCodeHide"
                style="color: red; font-size: xx-small;"
              >
                <i class="el-icon-warning" />医检条码号重复！</span
              >
            </el-form-item>
            <el-form-item label="平台条码号" prop="myReportCode">
              <el-input v-model.trim="reportForm.myReportCode"></el-input>
            </el-form-item>
  
            <el-form-item label="送检时间" prop="reportBeginTime">
              <el-date-picker
                v-model="reportForm.reportBeginTime"
                type="datetime"
                :picker-options="pickerBeginDateBefore"
                :default-value="timeDefaultShow"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="不填则默认为当前时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="报告状态" prop="reportState">
              <el-select
                v-model="reportForm.reportState"
                clearable
                reserve-keyword
                placeholder="请选择当前报告状态"
              >
                <el-option
                  v-for="item in pickCurReportStateList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="一级收样员" prop="syUserId">
              <el-select
                v-model="reportForm.syUserId"
                filterable
                clearable
                reserve-keyword
                placeholder="请选择一级收样员"
              >
                <el-option
                  v-for="item in pickSyUserList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
  
            <el-form-item label="二级收样员" prop="syUserIdTwo">
              <el-select
                v-model="reportForm.syUserIdTwo"
                filterable
                clearable
                reserve-keyword
                placeholder="请选择二级收样员"
              >
                <el-option
                  v-for="item in pickSyUserList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button
                @click="addSubclass()"
                icon="el-icon-plus"
                plain
                round
                type="success"
                size="mini"
              ></el-button>
            </el-form-item>
            <el-form-item
              prop="syUserIdList"
              v-for="(item, index) in reportForm.syUserIdList"
              :label="changSyUserLabel(index + 3)"
              :key="'syUserIdList' + index"
            >
              <el-select
                v-model.lazy="item.userId"
                filterable
                clearable
                reserve-keyword
                placeholder="请选择收样员"
              >
                <el-option
                  v-for="item in pickSyUserList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button
                @click="deleteSubclass(index)"
                icon="el-icon-close"
                plain
                round
                type="danger"
                size="mini"
              ></el-button>
            </el-form-item>
             <!-- 5.21 liusixiang 次级收样员 -->
            <!--:label="(3+index)+'级收样员'"-->
            <!-- v-if="index == 0" --给添加符号设置限制条件 -->
            <el-form-item label="是否需要结果提醒" prop="isRemind">
              <el-switch
                v-model="reportForm.isRemind"
                active-color="#13ce66"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
            <el-form-item label="是否加急" prop="priority">
              <el-switch
                v-model="reportForm.priority"
                active-color="#13ce66"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-row>
  
          <div class="tit">
            <h2>患者信息</h2>
          </div>
          <el-row>
            <el-form-item label="患者姓名" prop="patientName">
              <el-input v-model.trim="reportForm.patientName"></el-input>
            </el-form-item>
            <el-form-item label="患者性别" prop="patientSex">
              <el-radio-group v-model="reportForm.patientSex">
                <el-radio
                  :label="item.value"
                  :key="item.value"
                  v-for="item in sexLabels"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="患者身份证" prop="patientCard">
              <el-input
                v-model.trim="reportForm.patientCard"
                @change="cardChange"
              ></el-input>
            </el-form-item>
            <el-form-item label="证件类型" prop="cardType">
              <el-radio-group v-model="reportForm.cardType">
                <el-radio
                  :label="item.value"
                  :key="item.value"
                  @change="clickCardType(item.value)"
                  v-for="item in IdCardLabels"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="患者出生日期">
              <el-date-picker
                v-model="reportForm.birthday"
                type="date"
                placeholder="选择出生日期"
                value-format="yyyy-MM-dd"
                @change="getAgeByBirthday(reportForm.birthday)">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="患者年龄" prop="patientAge">
              <el-input
                v-model.trim="reportForm.patientAge"
              ></el-input>
            </el-form-item>
            <el-form-item label="患者手机号" prop="patientPhone">
              <el-input
                type="number"
                v-model.trim="reportForm.patientPhone"
                @change="phoneChange"
              ></el-input>
            </el-form-item>
            <el-form-item label="基本病情" prop="patientInfo">
              <el-input
                type="textarea"
                v-model="reportForm.patientInfo"
              ></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="reportForm.remark"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item>
                <el-button type="success" @click.native="sureReportClick(1)">保存并继续</el-button>
                <el-button type="primary" @click.native="sureReportClick(0)">保存并修改</el-button
                >
            </el-form-item>
            
          </el-row>
        </el-form>
        <!-- </div> -->
        <div class="right-content" >
            <h2 style="font-size: 20px;text-align: center;">报告单图片</h2>
            <el-row style="margin:40px 0" type="flex" justify="center" v-for="(item,index) in imageUrlList" :key="item">
                <div style="width:300px">
                    <img
                      :style="{width:'300px',transform:`scale(${zoomVal[index]})`}"
                      ref="imgChange"
                      @click="handleCheckImg(index)"
                      @dblclick="hanldeViewerImage(index)"
                      @mousewheel.prevent="bbimg($event,index)"
                      :src="item" 
                      title="双击预览图片"
                    >
                    <el-image-viewer
                        v-if="showViewer"
                        :initial-index="imgViewerIndex"
                        :on-close="()=>{showViewer = false}"
                        :url-list="imageUrlList">
                     </el-image-viewer>
                </div>
            </el-row>
        </div>
      </div>
  
      <el-dialog
        title="新增科室"
        :visible.sync="dialogOfficeFormVisible"
        :center="isCenter"
        width="500px"
      >
        <el-form :model="addOfficeForm">
          <el-form-item label="科室名称：" label-width="150px">
            <el-input
              v-model="addOfficeForm.officeName"
              autocomplete="off"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item align="center">
            <el-button @click.native="dismissOffice">取 消</el-button>
            <el-button type="primary" @click.native="commitOffice"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
  
      <el-dialog
        title="新增医生"
        :visible.sync="dialogDoctorFormVisible"
        :center="isCenter"
        width="500px"
      >
        <el-form :model="addDoctorForm">
          <el-form-item label="医生姓名：" label-width="150px">
            <el-input
              v-model="addDoctorForm.doctorName"
              autocomplete="off"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="医生职称：" label-width="150px">
            <el-input
              v-model="addDoctorForm.doctorTitle"
              autocomplete="off"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item align="center">
            <el-button @click.native="dismissDoctor">取 消</el-button>
            <el-button type="primary" @click.native="commitDoctor"
              >确 定</el-button
            >
          </el-form-item>
          
        </el-form>
      </el-dialog>
      <sameReportCheck
        ref="sameReportCheck"
        :dataList="sameReportList"
        @addReportSure="addReportSure"
      ></sameReportCheck>
    </div>
  </template>
  
  <script>
  import * as message from "@/constants/message";
  import SameReportCheck from "@/components/SameReportCheck";
  import Map from "@/components/Map";
  import { mapGetters, mapActions } from "vuex";
  import AuthApi from "@/api/system/auth";
  import ReportApi from "@/api/report/report";
  import OfficeApi from "@/api/institution/office";
  import HospitalApi from "@/api/institution/hospital";
  import HospitalItemApi from "@/api/institution/hospitalItem";
  import DoctorApi from "@/api/institution/doctor";
  import InstitutionApi from "@/api/institution/institution";
  import InstitutionItemApi from "@/api/institution/institutionItem";
  import TaskApi from "@/api/task/task"
  import { getStorage } from "@/utils/auth";
  import * as stn from "@/constants/storeName";
import { hidden } from "caniuse-lite/data/features";
import ElImageViewer from "element-ui/packages/image/src/image-viewer"
  
  export default {
    data() {
      return {
        zoomVal:[],
        imageList:[],
        imageUrlList:[], 
        showViewer:false,//是否展示预览图片
        imgViewerIndex:0, // 预览图片的索引
        IsContinue:false,
        sexLabels: [
          { label: "男", value: 1 },
          { label: "女", value: 2 }
        ],
        IdCardLabels: [
          { label: "居民省份证", value: 1 },
          { label: "其他", value: 9 }
        ],
        pickCurReportStateList: [
          { label: "已收取", value: 5 },
          { label: "已送达", value: 10 }
        ],
        loadingIns: false,
        loadingCla: false,
        loadingUpload: false,
        isForbidItemName:false,//是否禁用项目名称
        itemDisabled: true, // 选择特殊医院时禁用项目选择
        itemNameList: [], // 选择特殊医院的项目列表
        isCenter: true,
        pickHospitalList: [],
        pickOfficeList: [],
        pickDoctorList: [],
        pickHospitalItemList:[], //医院项目组列表
        pickInstitutionList: [],
        pickInsOfficeList: [],
        pickSyUserList: [],
        pickSampleTypeList: [],
        disabled: false,
        disabledBtn: false,
        userRole: "",
        dialogImageUrl: "",
        dialogImageAlt: "",
        dialogVisible: false,
        insCodeHide: true,
        dialogOfficeFormVisible: false,
        dialogDoctorFormVisible: false,
        addOfficeForm: {
          hospitalId: "",
          officeName: ""
        },
        addDoctorForm: {
          hospitalId: "",
          officeId: "",
          doctorName: "",
          doctorTitle: ""
        },
        reportForm: {
          taskImageId:"",
          reportTaskId:"",
          codeFlag: 1,
          myReportCode: "",
          searchCode: "",
          patientName: "",
          patientSex: "",
          patientAge: "",
          birthday:"",
          patientPhone: "",
          cardType: 1,
          patientCard: "",
          patientInfo: "",
          itemName: "",
          sampleTypeList: [],
          isRemind: "0",
          priority: "0",
          hospitalId: "",
          officeId: "",
          doctorId: "",
          hospitalItemIdList:[],//医院组合项目id
          institutionId: "",
          insOfficeId: "",
          insReportCode: "",
          reportState: "",
          syUserId: "",
          syUserIdTwo: "", //二级收样员
          syUserIdList: [], // 三级及其后续收样员
          reportBeginTime: "",
          remark: "",
          reportImageList: [],
          insItemIdList: []
        },
        reportFormTemporary:"", //存放reportFrom的初始化数据
        sampleTypeData: {
          sampleTypeOne: "",
          sampleTypeList: []
        },
        sameReportList: [], // 相同平台/医检条码号的旧报告单列表
        pickerBeginDateBefore: {
          disabledDate(time) {
            //return time.getTime() > Date.now();
          }
        },
        timeDefaultShow: "",
        roleRules: {
          institutionId:[
            {
              required: true,
              message: "请选择医检机构",
              trigger: "change"
            }
          ],
          itemName: [
            {
              required: true,
              message: "请输入或选择项目名称",
              trigger: "blur"
            }
          ],
          /*sampleTypeOne:[
            {
              required: true,
              message: "请选择检验样本",
              trigger:"blur"
            }
          ],*/
          patientName: [
            {
              required: true,
              message: "请输入患者姓名",
              trigger: "blur"
            }
          ],
          hospitalId: [
            {
              required: true,
              message: "请选择医院",
              trigger: "change"
            }
          ],
          cardType: [
            {
              required: true,
              message: "请选择证件类型",
              trigger: "change"
            }
          ],
          patientAge: [
            {
              pattern: /^([1-9]|[1-9]\d|1\d{2}|200)$/,
              message: "年龄输入错误",
              trigger: "blur"
            }
          ]
        }
      };
    },
    components: {
      Map,
      SameReportCheck,
      ElImageViewer
    },
    beforeRouteLeave(to, from, next) {
      to.meta.keepAlive = true;
      next();
    },
    methods: {
      ...mapGetters({
        openTabs: "getOpenTabs"
      }),
      ...mapActions({
        setOpenTabs: "setOpenTabs",
        setActiveIndexPath: "setActiveIndexPath",
        setDeleteTabs: "setDeleteTabs",
        replaceOpenTab: "replaceOpenTab"
      }),
      init() {
        
        this.$Utils.clearData(this.reportForm);
        this.reportForm.codeFlag = 1;
        this.reportForm.cardType = 1;
        this.reportForm.reportTaskId = this.$route.query.reportTaskId
        this.reportFormTemporary = JSON.stringify(this.reportForm) //保存初始的reportFrom,提交如果是保存并继续那么就必须要用
        this.getImageList()
        this.userInfo = getStorage(stn.USER_INFO);
        if (this.userInfo) {
          this.userRole = this.userInfo.userRole;
        }
        this.listHospital();
        this.listSyUser();
      },
      getImageList(){
        let cond = {
          reportTaskId:this.reportForm.reportTaskId,
          imageState:5,
          userId:1
        }
        TaskApi.getImageListByTaskId(cond).then(res=>{
          this.imageUrlList = res.data.map(item=>item.imageUrl)
          this.imageList = res.data
          for(let i=0;i<this.imageUrlList.length;i++){
            this.zoomVal.push(1)
          }
        })
      },
      bbimg(e,index) {
        // console.log()
        e = e || window.event
        for(let i=0;i<this.zoomVal.length;i++){
          if(i!=index){
            this.zoomVal[i] = 1
          }
        }
        
        this.zoomVal[index] += e.wheelDelta / 1200

        if(e.wheelDelta>0){
          this.$refs.imgChange.forEach(item=>item.style.visibility = 'hidden')
          this.$refs.imgChange[index].style.visibility = 'visible'
        }else{
          this.$refs.imgChange.forEach(item=>item.style.visibility = 'visible')
        }
        
        if (this.zoomVal[index] >= 0.9) {
          this.$set(this.zoomVal,index,this.zoomVal[index])
          // this.zoomVal[index] = this.zoomVal[index]
            // this.$refs.imgChange[index].style = `transform:scale(${this.zoomVal[index]});width:200px;height:200px;`
        } else {
          this.$set(this.zoomVal,index,1)
            // this.$refs.imgChange[index].style = `transform:scale(${this.zoomVal[index]});width:200px;height:200px`
            return false
        }
    },
    hanldeViewerImage(index){
      this.showViewer = true
      this.imgViewerIndex = index
    },
    handleCheckImg(index){
      this.$refs.imgChange.forEach(item=>item.style.outline="none")
      this.$refs.imgChange[index].style.outline ="4px solid #2B89FD" 
      this.reportForm.taskImageId = this.imageList[index].taskImageId
    },
      // 通过出生日期计算出年龄
      getAgeByBirthday(birthday){
        if(birthday){
          birthday = birthday.split('-')
          let date = new Date()
          let today = [date.getFullYear(),date.getMonth()+1,date.getDate()];
          let age = today.map((val,index)=>{
            return val - birthday[index]
          })
          if(age[2]<0){
            let lastMonth = new Date(today[0],today[1],0)
            age[1]--
            age[2]+=lastMonth.getDate()
          }
          if(age[1]<0){
            age[0]--
            age[1]+=12
          }
          this.reportForm.patientAge = age[0]
        }else{
          this.reportForm.patientAge = ""
        }
      },
      sureReportClick(IsContinue) {
        this.IsContinue = IsContinue
        this.$refs.reportForm.validate(valid => {
          if (valid) {
            if(!this.reportForm.taskImageId){
              this.$message.error("请选择一个报告单图片")
              return
            }
            // 收样员判断
            if (!this.reportForm.syUserId && this.reportForm.syUserIdTwo) {
              this.$message.error("请选择一级收样员");
              return;
            }
            let syList = this.reportForm.syUserIdList;
            if (syList && syList.length > 0) {
              if (!this.reportForm.syUserId) {
                this.$message.error("请选择一级收样员");
                return;
              }
              if (!this.reportForm.syUserIdTwo) {
                this.$message.error("请选择二级收样员");
                return;
              }
              let syListTwo = syList.filter(item => {
                return item.userId != null;
              });
              if (syList.length !== syListTwo.length) {
                this.$message.error("请选择多级收样员");
                return;
              }
            }
            // 如果是广东祈福医院那么患者身份证或者性别、年龄、出生日期必须选择一个填写完整
              if(this.reportForm.institutionId==124){
                if((!this.reportForm.patientSex||!this.reportForm.birthday||!this.reportForm.patientAge)&&!this.reportForm.patientCard){
                  this.$message.error("请输入完整性别、年龄、出生日期或者输入身份证")
                  return
                }
              }
  
            // 如果是医检项目那么必须填写项目
            if(!this.itemDisabled){
              if(this.reportForm.insItemIdList.length<1){
                this.$message.error("请选择医检项目")
                return
              }
            }
              
            this.$confirm(
              message.MSG_CONFIRM_SAVE_ALTER,
              message.TITLE_PROMPT,
              {}
            ).then(() => {
              // 判断是否同号
              this.addBeforeCheck();
              // add
              //this.addReport()
            });
          }
        });
      },
      checkInsCodeIsExist() {
        let _this = this;
        if (
          _this.reportForm.insReportCode !== "" &&
          _this.reportForm.insReportCode !== null
        ) {
          _this.insCodeHide = true;
          if (!_this.reportForm.institutionId) {
            this.$message.error("请选择医检机构");
            return;
          }
          let cond = {
            institutionId: _this.reportForm.institutionId,
            insReportCode: _this.reportForm.insReportCode
          };
          ReportApi.getReportCount(cond)
            .then(res => {
              if (res.data && res.data > 0) {
                _this.insCodeHide = false;
              }
            })
            .catch(error => {
              _this.insCodeHide = true;
              console.error(error);
            });
        }
      },
      listInstitution() {
        let _this = this;
        _this.loadingIns = true;
        // 判断医院项目是否存在如果存在那么就
        if(_this.reportForm.hospitalItemIdList.length>0){
          let cond = {
            hosItemIds: this.reportForm.hospitalItemIdList+''
          };
          InstitutionApi.listInsByHosItemId(cond)
            .then(res => {
              setTimeout(() => {
                _this.loadingIns = false;
                _this.pickInstitutionList  = res.data.map(item => {
                  return {
                    value: item.institutionId,
                    label: item.institutionName
                  };
                });
              }, 200);
            })
            .catch(error => {
              _this.pickInstitutionList = [];
              console.error(error);
            });
        }else{
          let cond = {
            hospitalId: this.reportForm.hospitalId
          };
          InstitutionApi.getInsByHos(cond)
            .then(res => {
              setTimeout(() => {
                _this.loadingIns = false;
                _this.pickInstitutionList = res.data.map(item => {
                  return {
                    value: item.institutionId,
                    label: item.institutionName
                  };
                });
              }, 200);
            })
            .catch(error => {
              _this.pickInstitutionList = [];
              console.error(error);
            });
        }
        
      },
      institutionChange() {
        let _this = this;
        _this.pickInsOfficeList = [];
        _this.reportForm.insOfficeId = "";
        let cond = {
          institutionId: _this.reportForm.institutionId
        };
        OfficeApi.getOfficeNames(cond).then(res => {
          setTimeout(() => {
            _this.pickInsOfficeList = res.data.map(item => {
              return {
                value: item.officeId,
                label: item.officeName
              };
            });
          }, 200);
        });
        InstitutionApi.insSampleTypes(cond)
          .then(res => {
            setTimeout(() => {
              _this.pickSampleTypeList = res.data.map(item => {
                return {
                  value: item.insSampleCode,
                  label: item.insSampleName
                };
              });
            }, 200);
          })
          .catch(error => {
            _this.pickSampleTypeList = [];
            console.error(error);
          });
  
        // 97/100 分别表示 重庆两家机构  101：珠海九龙
        if (
          _this.reportForm.institutionId == 97 ||
          _this.reportForm.institutionId == 100 ||
          _this.reportForm.institutionId == 112 ||
          _this.reportForm.institutionId == 124
        ) {
          //if(_this.reportForm.institutionId == 100){
          
          InstitutionItemApi.listInsItemNameAndGroup(cond)
            .then(res => {
              setTimeout(() => {
                this.itemNameList = res.data.map(item => {
                  return {
                    value: item.itemId,
                    label: item.itemName + "-" + item.itemGroup
                  };
                });
              }, 200);
            })
            .catch(error => {
              _this.itemNameList = [];
              console.error(error);
            });
            this.itemDisabled = false;
            this.isForbidItemName = false
            _this.reportForm.itemName = ""
            _this.reportForm.insItemIdList = []
            // 当切换到医检项目的时候，如果医院项目存在要清空医院名称医院项目还有项目名称这些数据
            if(_this.reportForm.hospitalItemIdList.length>0){
                _this.reportForm.hospitalId = "";
  
                _this.reportForm.hospitalItemIdList = []
                _this.pickHospitalItemList = []
  
               
              
            }
  
        }else{
           _this.itemNameList = []
          this.itemDisabled = true;
        }
      },
      itemListChange(value) {
        let _this = this; 
        if(value.length>0){
          this.isForbidItemName = true
        }else{
          this.isForbidItemName = false
        }
        
        // 首先遍历每一个value值 在用每一个value值去找对应的label
        if (value != undefined || value.length >= 0) {
          var newList = [];
          value.forEach(item => {
            let choseValue = item;
            var choseList = _this.itemNameList.find(item => {
              return item.value == choseValue;
            });
            newList.push(choseList.label);
          });
          _this.reportForm.itemName = newList.join("，");
          // 珠海可允许一个条码号绑定不同类型的项目，一个条码号可以扫多次
          if (_this.reportForm.institutionId == 112) {
            return;
          }
  
          // 筛选出相同科室的项目
          if (value.length == 0 || value.length == 1) {
            let cond = {
              institutionId: _this.reportForm.institutionId
            };
            if (value.length == 1) {
              cond.itemId = value[0];
            }
            InstitutionItemApi.listInsItemNameAndGroup(cond)
              .then(res => {
                setTimeout(() => {
                  _this.itemNameList = res.data.map(item => {
                    return {
                      value: item.itemId,
                      label: item.itemName + "-" + item.itemGroup
                    };
                  });
                }, 200);
              })
              .catch(error => {
                _this.itemNameList = [];
                console.error(error);
              });
          }
         
        }
      },
      listHospital() {
        let _this = this;
        _this.loadingIns = true;
        let cond = {
          hospitalType: 1
        };
        HospitalApi.getHospitalNameList(cond).then(res => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickHospitalList = res.data.map(item => {
              return {
                value: item.hospitalId,
                label: item.hospitalName
              };
            });
          }, 200);
        });
      },
      hospitalChange() {
        let _this = this;
        _this.pickOfficeList = [];
        _this.reportForm.officeId = "";
        _this.pickDoctorList = [];
        _this.reportForm.doctorId = "";
        _this.pickInstitutionList = [];
        _this.reportForm.institutionId = "";
        // _this.reportForm.syUserId = "";
        _this.pickHospitalItemList = [];
        _this.reportForm.hospitalItemIdList = [];
        _this.reportForm.itemName = "";
        _this.reportForm.insItemIdList = [];
        _this.itemNameList = [];
        _this.itemDisabled = true;
        _this.isForbidItemName = false
        if (
          _this.reportForm.hospitalId == "" ||
          _this.reportForm.hospitalId == null
        ) {
          _this.$message.error("请先选择医院");
          return;
        }
        
        
        //_this.loadingCla = true
        let cond = {
          hospitalId: _this.reportForm.hospitalId
        };
        OfficeApi.getOfficeNames(cond).then(res => {
          setTimeout(() => {
            _this.pickOfficeList = res.data.map(item => {
              return {
                value: item.officeId,
                label: item.officeName
              };
            });
          }, 200);
        });
  
        // 获取医院组合项目列表
        HospitalItemApi.listHospitalItemsName(cond).then(res=>{
          setTimeout(() => {
            _this.pickHospitalItemList = res.data.map(item => {
              return {
                value: item.itemId,
                label: item.itemName
              };
            });
          }, 200);
        })
      },
      officeChange() {
        let _this = this;
        _this.pickDoctorList = [];
        _this.reportForm.doctorId = "";
        if (
          _this.reportForm.hospitalId == "" ||
          _this.reportForm.hospitalId == null
        ) {
          _this.$message.error("请先选择医院");
          return;
        }
        if (
          _this.reportForm.officeId == "" ||
          _this.reportForm.officeId == null
        ) {
          _this.$message.error("请先选择科室");
          return;
        }
        //_this.loadingCla = true
        let cond = {
          hospitalId: _this.reportForm.hospitalId,
          officeId: _this.reportForm.officeId
        };
        DoctorApi.getDoctorNames(cond).then(res => {
          setTimeout(() => {
            _this.pickDoctorList = res.data.map(item => {
              return {
                value: item.doctorId,
                label: item.doctorName
              };
            });
          }, 200);
        });
      },
      // 医院项目改变
      hospitalItemChange(listId){
        this.pickInstitutionList = [];
          this.reportForm.institutionId = "";
          this.reportForm.itemName = ""
          this.itemDisabled = true;
          let arr = []
          
          if(listId.length>0){
            this.pickHospitalItemList.forEach(item=>{
              if(listId.some(id=>item.value==id)){
                arr.push(item.label)
              }
            })
            this.reportForm.itemName = arr.join(",")
            this.isForbidItemName = true
          }else{
             this.isForbidItemName = false
          }
          // this.pickInstitutionList = [];
          // this.reportForm.institutionId = "";
          // let index = this.pickHospitalItemList.findIndex(item=>item.value == id)
          // if(index>=0){
          //   this.reportForm.itemName = this.pickHospitalItemList[index].label
          // }else{
          //   this.reportForm.itemName = ""
          // }
          this.itemDisabled = true;
          
      },
      // 获取用户列表
      listSyUser() {
        let _this = this;
        AuthApi.listAdminByRole({
          roleId: 4
        }).then(res => {
          setTimeout(() => {
            this.pickSyUserList = res.data.map(item => {
              return {
                value: item.userId,
                label: item.userName
              };
            });
          }, 200);
        });
      },
      // 无限增加次级收样员
      addSubclass() {
        if (!this.reportForm.syUserId) {
          this.$message.error("请选择一级收样员");
          return;
        }
        if (!this.reportForm.syUserIdTwo) {
          this.$message.error("请选择二级收样员");
          return;
        }
        let data = { userId: null };
        this.reportForm.syUserIdList.push(data);
      },
      // 删除次级收样员
      deleteSubclass(index) {
        this.reportForm.syUserIdList.splice(index, 1);
      },
      // 显示多级收样员label
      changSyUserLabel(index) {
        let result = this.$Utils.numberToChinese(index);
        return result + "级收样员";
      },
      addSubSampleType() {
        let data = { id: null };
        this.sampleTypeData.sampleTypeList.push(data);
      },
      deleteSubSampleType(index) {
        this.sampleTypeData.sampleTypeList.splice(index, 1);
      },
      addOffice() {
        let _this = this;
        if (
          _this.reportForm.hospitalId == "" ||
          _this.reportForm.hospitalId == null
        ) {
          _this.$message.error("请先选择医院");
          return;
        }
        this.dialogOfficeFormVisible = true;
        _this.addOfficeForm.hospitalId = _this.reportForm.hospitalId;
      },
      dismissOffice() {
        this.dialogOfficeFormVisible = false;
        this.addOfficeForm.hospitalId = "";
        this.addOfficeForm.officeName = "";
      },
      commitOffice() {
        let _this = this;
        var str = _this.addOfficeForm.officeName.replace(/(^\s*)|(\s*$)/g, ""); //去除空格
        if (str == "" || str == undefined || str == null) {
          _this.$message.error("请输入科室名称");
          return;
        }
        OfficeApi.addOffice(this.addOfficeForm).then(res => {
          _this.dialogOfficeFormVisible = false;
          this.$Utils.notifySuccess();
          this.hospitalChange();
        });
      },
      addDoctor() {
        let _this = this;
        if (
          _this.reportForm.hospitalId == "" ||
          _this.reportForm.hospitalId == null
        ) {
          _this.$message.error("请先选择医院");
          return;
        }
        if (
          _this.reportForm.officeId == "" ||
          _this.reportForm.officeId == null
        ) {
          _this.$message.error("请先选择科室");
          return;
        }
        this.dialogDoctorFormVisible = true;
        _this.addDoctorForm.hospitalId = _this.reportForm.hospitalId;
        _this.addDoctorForm.officeId = _this.reportForm.officeId;
      },
      dismissDoctor() {
        this.dialogDoctorFormVisible = false;
        this.addDoctorForm.hospitalId = "";
        this.addDoctorForm.officeId = "";
        this.addDoctorForm.doctorName = "";
        this.addDoctorForm.doctorTitle = "";
      },
      commitDoctor() {
        let _this = this;
        var str = _this.addDoctorForm.doctorName.replace(/(^\s*)|(\s*$)/g, ""); //去除空格
        if (str == "" || str == undefined || str == null) {
          _this.$message.error("请输入医生姓名");
          return;
        }
        var strTitle = _this.addDoctorForm.doctorTitle.replace(
          /(^\s*)|(\s*$)/g,
          ""
        ); //去除空格
        if (strTitle == "" || strTitle == undefined || strTitle == null) {
          _this.addDoctorForm.doctorTitle = "无";
          /*this.$notify.error({
            title: '错误',
            message: '请输入医生职称'
          });
          return;*/
        }
        DoctorApi.addDoctor(_this.addDoctorForm).then(res => {
          _this.dialogDoctorFormVisible = false;
          _this.$Utils.notifySuccess();
          _this.officeChange();
        });
      },
      // 新增过程中的表单校验
  
      // 当电话号码以及身份证号码输入框发生改变 且不为空时 校验该内容的合法性
      phoneChange(val) {
        if (!this.$Utils.isEmptyObject(val)) {
          if (!this.$Utils.isMobile(val)) {
            this.$Utils.messageError("电话号码格式错误");
            this.disabledBtn = true;
          } else {
            this.disabledBtn = false;
          }
        } else {
          this.disabledBtn = false;
        }
      },
      clickCardType(val) {
        if (val == 9) {
          this.disabledBtn = false;
        }
      },
      cardChange(val) {
        if (!this.$Utils.isEmptyObject(val)) {
          if (!this.$Utils.isCardNo(val) && this.reportForm.cardType == 1) {
            this.$Utils.messageError("身份证号码格式错误");
            this.disabledBtn = true;
          } else {
            this.disabledBtn = false;
          }
        } else {
          this.disabledBtn = false;
        }
      },
      addBeforeCheck() {
        let _this = this;
        let reportFormData = {
          isAdd: true,
          myReportCode: _this.reportForm.myReportCode,
          itemName: _this.reportForm.itemName,
          hospitalId: _this.reportForm.hospitalId,
          officeId: _this.reportForm.officeId,
          doctorId: _this.reportForm.doctorId,
          hosItemIds:_this.reportForm.hospitalItemIdList, //医院项目id
          institutionId: _this.reportForm.institutionId,
          insReportCode: _this.reportForm.insReportCode,
          patientName: _this.reportForm.patientName,
          patientSex: _this.reportForm.patientSex,
          patientAge: _this.reportForm.patientAge,
        };
        ReportApi.checkReportAdd(reportFormData).then(res => {
          let data = res.data;
          // remindType提醒类型（1.3天内录有同医院同名提醒）
          if (data.remindType == 1) {
            this.$confirm(data.remindMsg, message.MSG_CONFIRM_IS_CONTINUE, {
              confirmButtonText: "继续",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                if (data.reportList && data.reportList.length > 0) {
                  _this.sameReportList = data.reportList;
                  this.$refs.sameReportCheck.handleCreate();
                } else {
                  this.addReport();
                }
              })
              .catch(() => {
                this.$message.info("已取消");
              });
          } else {
            if (data.reportList && data.reportList.length > 0) {
              _this.sameReportList = data.reportList;
              this.$refs.sameReportCheck.handleCreate();
            } else {
              this.addReport();
            }
          }
        });
      },
      addReportSure() {
        this.reportForm.codeFlag = 2;
        this.addReport();
      },
      addReport() {
        let _this = this;
  
        // 项目样本类型
        let sampleTypeList = [];
        if (!_this.$Utils.isNull(_this.sampleTypeData.sampleTypeOne)) {
          sampleTypeList.push(_this.sampleTypeData.sampleTypeOne);
        }
        if (!_this.$Utils.isNull(_this.sampleTypeData.sampleTypeList)) {
          if (_this.sampleTypeData.sampleTypeList.length > 0) {
            _this.sampleTypeData.sampleTypeList.forEach(a => {
              sampleTypeList.push(a.id);
            });
          }
        }
        let reportFormData = {
          codeFlag: _this.reportForm.codeFlag,
          myReportCode: _this.reportForm.myReportCode,
          searchCode: _this.reportForm.searchCode,
          patientName: _this.reportForm.patientName,
          patientSex: _this.reportForm.patientSex,
          birthday:_this.reportForm.birthday,
          patientAge: _this.reportForm.patientAge,
          patientPhone: _this.reportForm.patientPhone,
          cardType: _this.reportForm.cardType,
          patientCard: _this.reportForm.patientCard,
          patientInfo: _this.reportForm.patientInfo,
          remark: _this.reportForm.remark,
          itemName: _this.reportForm.itemName,
          insItemIdList: _this.reportForm.insItemIdList,
          sampleCodeList:sampleTypeList,
  
          isRemind: parseInt(_this.reportForm.isRemind),
          priority: parseInt(_this.reportForm.priority),
          hospitalId: _this.reportForm.hospitalId,
          officeId: _this.reportForm.officeId,
          doctorId: _this.reportForm.doctorId,
          hosItemIds:_this.reportForm.hospitalItemIdList, //医院项目id
          institutionId: _this.reportForm.institutionId,
          insOfficeId: _this.reportForm.insOfficeId,
          insReportCode: _this.reportForm.insReportCode,
          syUserId: _this.reportForm.syUserId,
          syUserIdTwo: _this.reportForm.syUserIdTwo, //二级收样员
          syUserIdList: _this.reportForm.syUserIdList, // 第三级收样员开始的数组对象
          reportState: _this.reportForm.reportState,
          reportBeginTime: _this.reportForm.reportBeginTime,
          reportImageList: _this.reportForm.reportImageList,

          reportTaskId:_this.reportForm.reportTaskId,
          taskImageId:_this.reportForm.taskImageId,
        };
        ReportApi.addReport(reportFormData).then(data => {
          _this.$Utils.notifySuccess();
          this.getImageList()
          if(_this.IsContinue){ //1就是保存并继续,0就是保存并修改
            // TaskApi.getImageListByTaskId(cond).then(res=>{
            //   _this.zoomVal = []
            //   _this.imageUrlList = res.data.map(item=>item.imageUrl)
            //   _this.imageList = res.data
            //     for(let i=0;i<_this.imageUrlList.length;i++){
            //       _this.zoomVal.push(1)
            //     }
                _this.reportForm = JSON.parse(_this.reportFormTemporary)
            //  })
          }else{
            _this.returnList();
          }
          
        });
      },
      handleRemove(file, fileList) {
        if (file.response) {
          const url = file.response.url;
          this.reportForm.reportImageList.splice(
            this.reportForm.reportImageList.indexOf(url),
            1
          );
        }
      },
      handlePictureCardPreview(file) {
        //this.dialogImageUrl = file.url
        this.dialogImageUrl = "/static/img/pdfdefault.jpg";
        this.dialogImageAlt = file.name;
        this.dialogVisible = true;
      },
      returnList() {
        this.$store.dispatch("delView", this.$route);
        //this.$router.go(-1);
        this.$router.push({ path: "/task/taskManagement" });
      }
    },
    mounted() {
      this.timeDefaultShow = new Date();
      this.reportForm.patientSex = 1;
      this.reportForm.cardType = 1;
      this.init();
    }
  };
  </script>
  <style lang="scss" src="@/assets/css/views/add.scss" scope></style>
  <style lang="scss" scoped>
  .main_box {
    position: absolute;
    width: calc(100% - 50px);
    height: calc(100vh - 113px);
    overflow: auto;
    border: 1px solid #e6e6e6;
    margin: 10px;
  }
  .add_wrap {
    border: none;
    padding-top: 10px;
    .right-content{
        box-sizing: border-box;
        right: 0;
        position: fixed;
        top: 100px;
        height:700px;
        width:30%;
        overflow: auto;
        margin-left: 100px;
        margin-right: 40px;
        &::-webkit-scrollbar{
          width: 10px;
          height: 10px;
          background-color: #F1F1F1;
        }
        &::-webkit-scrollbar-thumb{
          background-color:  #C1C1C1;
        }
        &::-webkit-scrollbar-track{
          border-radius: 4px;
        }
    }
  }
  </style>
  